package fun.codedesign.jdk.lang.lambda;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ListGroup {

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1L, "zhangsan", 23, new BigDecimal(55)));
        userList.add(new User(2L, "lisi", 33, new BigDecimal(22)));
        userList.add(new User(3L, "wangwu", 44, new BigDecimal(44)));
        userList.add(new User(4L, "mazi", null, new BigDecimal(44)));
        userList.add(new User(4L, "hello", null, new BigDecimal(32), "female"));
        userList.add(new User(4L, "world2", null, new BigDecimal(66), "female"));

        // 对年龄进行统计
        int ageCount = userList.stream()
                .mapToInt(item -> item.getAge() == null ? 0 : item.getAge())
                .sum();
        System.out.println("年龄总和： " + ageCount);
        // 对资产进行统计
        BigDecimal amounts1 = userList
                .stream()
                .map(item -> item.getAmount() == null ? BigDecimal.ZERO : item.getAmount())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("资产总和1 :" + amounts1);

        // 对资产进行统计 (这种方式会存在空指针异常，所以建议还是使用上面一种方式 )
        BigDecimal amounts2 = userList
                .stream()
                .map(User::getAmount)
                .reduce(BigDecimal::add)
                .get();

        System.out.println("资产总和2: " + amounts2);

        // 根据性别分组
        Map<String, List<User>> groupByGender = userList
                .stream()
                .collect(Collectors.groupingBy(User::getGender));
        System.out.println("male:" + groupByGender.get("male").size());
        System.out.println("female:" + groupByGender.get("female").size());
    }

    public static class User {

        private Long id;
        private String name;
        private Integer age;
        private BigDecimal amount;
        private String gender = "male";

        public User() {
        }

        public User(Long id, String name) {
            this.id = id;
            this.name = name;
        }

        public User(Long id, String name, Integer age, BigDecimal amount) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.amount = amount;
        }

        public User(Long id, String name, Integer age, BigDecimal amount, String gender) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.amount = amount;
            this.gender = gender;
        }

        public Integer getAge() {
            return age;
        }

        public BigDecimal getAmount() {
            return amount;
        }

        public Long getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getGender() {
            return gender;
        }
    }
}